package handler

import (
	"net/http"

	"gitee.com/fu-ce-wei/pi-mapper/internal/service"
	"github.com/gin-gonic/gin"
)

// TaskHandler 任务处理器
type TaskHandler struct {
	scanService service.ScanService
}

// NewTaskHandler 创建任务处理器实例
func NewTaskHandler(scanService service.ScanService) *TaskHandler {
	return &TaskHandler{
		scanService: scanService,
	}
}

// TriggerScan 触发文件扫描
func (h *TaskHandler) TriggerScan(c *gin.Context) {
	// 异步执行扫描任务
	go func() {
		ctx := c.Request.Context()
		if err := h.scanService.ScanVideoFiles(ctx); err != nil {
			// 这里可以添加错误通知机制
		}
	}()

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "扫描任务已启动",
	})
}

// GetTaskStatus 获取任务状态
func (h *TaskHandler) GetTaskStatus(c *gin.Context) {
	status, err := h.scanService.GetTaskStatus(c.Request.Context())
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": http.StatusInternalServerError,
			"msg":  "获取任务状态失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "success",
		"data": status,
	})
}

// GetHealth 健康检查
func (h *TaskHandler) GetHealth(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "healthy",
		"data": map[string]string{
			"status": "ok",
		},
	})
}
